package com.brillilab.starter.controller.aio.kit;

import com.alibaba.fastjson.JSONObject;
import com.brillilab.common.constant.ResultEnum;
import com.brillilab.common.entity.PageVo;
import com.brillilab.common.entity.ResponseVo;
import com.brillilab.common.exceptions.BrillilabException;
import com.brillilab.domain.enums.experiment.UsageOperationEnum;
import com.brillilab.domain.enums.kit.KitTakeType;
import com.brillilab.domain.enums.kit.UnLockOperateEnum;
import com.brillilab.domain.pa.experiments.PrintPreviewGet;
import com.brillilab.domain.po.experiments.ExperimentStepReagent;
import com.brillilab.domain.po.kit.Kit;
import com.brillilab.domain.vo.experiments.ExperimentKitUsageListVo;
import com.brillilab.domain.vo.kit.*;
import com.brillilab.domain.vo.lock.ItemLock;
import com.brillilab.domain.vo.print.KitUsageItemPrintVo;
import com.brillilab.domain.vo.user.UserInfoVo;
import com.brillilab.service.core.kit.IKitService;
import com.brillilab.service.core.space.IDeviceService;
import com.brillilab.service.logic.inventory.ReagentInventoryLogic;
import com.brillilab.service.logic.kit.KitUsageLogic;
import com.brillilab.service.logic.user.UsersLogic;
import com.brillilab.starter.aspect.AspectLog;
import com.brillilab.starter.constant.StarterConstant;
import com.brillilab.starter.entity.req.kit.KitUsageAddList;
import com.brillilab.starter.entity.req.kit.KitUsageQrReq;
import com.brillilab.starter.entity.req.kit.KitUsageRemoveReq;
import com.brillilab.starter.entity.req.kit.UsageUnlockReq;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 取用/待归还清单Controller
 *
 * @author wmh
 */
@RestController
@RequestMapping(value="/api/kitUsage")
@Slf4j
public class KitUsageController {

    @Resource
    private UsersLogic usersLogic;
    @Resource
    private KitUsageLogic kitUsageLogic;
    @Resource
    private IKitService kitService;
    @Resource
    private IDeviceService deviceService;
    @Resource
    private ReagentInventoryLogic reagentInventoryLogic;

    /**
     * 试剂成分加入取用清单
     *
     * @return
     */
    @AspectLog
    @RequestMapping(value="/take/add", method=RequestMethod.POST)
    public ResponseVo addInventoryToTakeList(@RequestBody KitUsageAddList kitUsageAddList,@RequestHeader(name=StarterConstant.TOKEN) String token) {

        Assert.isTrue(kitUsageAddList != null,"请求参数缺失！");
        List<KitUsageAdd> kitUsageAdds=kitUsageAddList.getItems();
        Assert.isTrue(!CollectionUtils.isEmpty(kitUsageAdds) && !StringUtils.isBlank(token),"请求参数缺失！");

        UserInfoVo userInfo=usersLogic.getUserByToken(token);

        //试剂成分加入取用清单
        kitUsageLogic.addInventoryToTakeList(userInfo,kitUsageAdds);

        return ResponseVo.success();
    }

    /**
     * 试剂成分取用
     *
     * @return
     */
    @AspectLog
    @RequestMapping(value="/usage/add", method=RequestMethod.POST)
    public ResponseVo addInventoryToUsageList(@RequestBody KitUsageAddList kitUsageAddList,@RequestHeader(name=StarterConstant.TOKEN) String token) {

        Assert.isTrue(kitUsageAddList != null,"请求参数缺失！");
        List<KitUsageAdd> kitUsageAdds=kitUsageAddList.getItems();
        Assert.isTrue(!CollectionUtils.isEmpty(kitUsageAdds) && !StringUtils.isBlank(token),"请求参数缺失！");

        UserInfoVo userInfo=usersLogic.getUserByToken(token);

        //设备是否有锁
        List<KitUsageAdd> hasLocks=new ArrayList<>();
        List<KitUsageAdd> noLocks=new ArrayList<>();
        List<Long> invIds=kitUsageAdds.stream().map(KitUsageAdd::getInventoryId).collect(Collectors.toList());
        List<ItemLock> itemLocks=deviceService.selectDeviceLockMapByInvId(invIds);
        kitUsageAdds.forEach(kitUsageAdd -> {
            Assert.isTrue(kitUsageAdd.getInventoryId() != null,"请求参数缺失！");
            ItemLock itemLock=itemLocks.stream().filter(e -> e.getId().equals(kitUsageAdd.getInventoryId())).findFirst().orElse(null);
            if(itemLock != null && itemLock.getHasLock().equals(1)){
                hasLocks.add(kitUsageAdd);
            } else {
                noLocks.add(kitUsageAdd);
            }
        });

        if(noLocks.size() > 0){
            kitUsageLogic.addInventoryToNotReturnList(userInfo,noLocks);
        }

        if(hasLocks.size() > 0){
            kitUsageLogic.addInventoryToTakingList(userInfo,hasLocks);
        }

        return ResponseVo.success();
    }

    /**
     * 从清单中取用
     *
     * @return
     */
    @AspectLog
    @RequestMapping(value="/take/use", method=RequestMethod.POST)
    public ResponseVo takeUse(@RequestBody KitUsageAddList kitUsageAddList,@RequestHeader(value=StarterConstant.TOKEN) String token) {

        Assert.isTrue(kitUsageAddList != null,"请求参数缺失！");
        List<KitUsageAdd> kitUsageAdds=kitUsageAddList.getItems();
        Assert.isTrue(!CollectionUtils.isEmpty(kitUsageAdds),"请求参数缺失！");

        UserInfoVo userInfo=usersLogic.getUserByToken(token);

        String endPoint = token.split("_")[0];

        doUse(kitUsageAdds,userInfo,endPoint);

        return ResponseVo.success();
    }

    private void doUse(List<KitUsageAdd> kitUsageAdds,UserInfoVo userInfo,String endPoint) {
        List<KitUsageAdd> hasLocks=new ArrayList<>();
        List<KitUsageAdd> noLocks=new ArrayList<>();
        List<Long> invIds=kitUsageAdds.stream().map(KitUsageAdd::getUsageId).collect(Collectors.toList());
        List<ItemLock> itemLocks=deviceService.selectDeviceLockMapByUsageId(invIds);
        kitUsageAdds.forEach(kitUsageAdd -> {
            Assert.isTrue(kitUsageAdd.getUsageId() != null,"请求参数缺失！");
            ItemLock itemLock=itemLocks.stream().filter(e -> e.getId().equals(kitUsageAdd.getUsageId())).findFirst().orElse(null);
            if(itemLock != null && itemLock.getHasLock().equals(1)){
                hasLocks.add(kitUsageAdd);
            } else {
                noLocks.add(kitUsageAdd);
            }
        });

        //设备是否有锁
        if(noLocks.size() > 0){
            kitUsageLogic.kitTakeToKitNotReturn(noLocks,userInfo,endPoint);
        }

        if(hasLocks.size() > 0){
            kitUsageLogic.kitTakeToTaking(hasLocks,userInfo);
        }
    }

    /**
     * 清单 取用/归还/清空操作
     */
    @AspectLog
    @RequestMapping(value="/list/operation", method=RequestMethod.POST)
    public ResponseVo listOperation(@RequestBody List<KitUsageOperateVo> operates,@RequestHeader(name=StarterConstant.TOKEN) String token) {

        Assert.isTrue(operates != null && operates.size() > 0 && StringUtils.isNotBlank(token),"请求参数缺失！");

        UserInfoVo userInfo=usersLogic.getUserByToken(token);

        String endPoint = token.split("_")[0];

        operates.forEach(operate -> {
            Assert.isTrue(operate.getAmount() != null && operate.getUsageId() != null && operate.getOperation() != null,"请求参数缺失！");
        });

        //取用
        List<KitUsageAdd> use=operates.stream()
                .filter(e -> e.getOperation().equals(UsageOperationEnum.USE.getValue()))
                .map(operate -> {
                    KitUsageAdd kitUsageAdd=new KitUsageAdd();
                    kitUsageAdd.setUsageId(operate.getUsageId());
                    kitUsageAdd.setAmount(operate.getAmount());
                    return kitUsageAdd;
                }).collect(Collectors.toList());
        if(use.size()>0){
            doUse(use,userInfo,endPoint);
        }

        //归还
        List<KitUsageReturn> rtn=operates.stream()
                .filter(e -> e.getOperation().equals(UsageOperationEnum.RETURN.getValue()) || e.getOperation().equals(UsageOperationEnum.EMPTY.getValue()))
                .map(operate -> {
                    KitUsageReturn kitUsageReturn=new KitUsageReturn();
                    kitUsageReturn.setUsageId(operate.getUsageId());
                    kitUsageReturn.setUseAmount(operate.getAmount());
                    kitUsageReturn.setType(operate.getOperation());
                    return kitUsageReturn;
                })
                .collect(Collectors.toList());
        if(rtn.size()>0){
            doReturn(rtn,userInfo,endPoint);
        }

        return ResponseVo.success();
    }

    /**
     * 清单
     *
     * @return
     */
    @RequestMapping(value="/list", method=RequestMethod.GET)
    public ResponseVo getManifestList(@RequestHeader(name=StarterConstant.TOKEN) String token) {

        Assert.isTrue(!StringUtils.isBlank(token),"请求参数缺失！");

        UserInfoVo userInfo=usersLogic.getUserByToken(token);

        //取用清单列表
        KitUsageListVo manifestList=kitUsageLogic.getManifestList(userInfo.getLabId(),userInfo.getLabMemberId());

        return ResponseVo.success(manifestList);
    }

    /**
     * 取用清单列表
     *
     * @return
     */
    @RequestMapping(value="/take/list", method=RequestMethod.GET)
    public ResponseVo getTakeList(@RequestHeader(name=StarterConstant.TOKEN) String token) {

        Assert.isTrue(!StringUtils.isBlank(token),"请求参数缺失！");

        UserInfoVo userInfo=usersLogic.getUserByToken(token);

        //取用清单列表
        KitUsageTakeList result=kitUsageLogic.getTakeList(userInfo.getLabId(),userInfo.getLabMemberId());

        return ResponseVo.success(result);
    }

    /**
     * 取用中列表
     *
     * @param token
     * @return
     * @time 2019-02-15
     */
    @RequestMapping(value="/taking/list", method=RequestMethod.GET)
    public ResponseVo getTakingList(@RequestHeader(name=StarterConstant.TOKEN) String token) {

        Assert.isTrue(!StringUtils.isBlank(token),"请求参数缺失！");

        UserInfoVo userInfo=usersLogic.getUserByToken(token);

        //取用清单列表
        List<KitTakeDeviceList> result=kitUsageLogic.getTakingList(userInfo.getLabId(),userInfo.getLabMemberId());

        return ResponseVo.success(result);
    }

    /**
     * 登录/未登录扫描待归还列表
     *
     * @return
     */
    @RequestMapping(value="/usage/list", method=RequestMethod.GET)
    public ResponseVo getUsageList(KitUsageQrReq req, @RequestHeader(name=StarterConstant.TOKEN) String token) {

        Long labId;
        Long labMemberId;
        Date usageTime=null;
        if(req.getLabId() == null && req.getLabMemberId() == null && req.getUsageTime() == null){
            Assert.isTrue(!StringUtils.isBlank(token),"请求参数缺失！");
            UserInfoVo userInfo=usersLogic.getUserByToken(token);
            if(userInfo == null){
                return ResponseVo.failure(ResultEnum.USER_NOT_LOGIN);
            }
            labId=userInfo.getLabId();
            labMemberId=userInfo.getLabMemberId();
        } else {
            Assert.isTrue(req.getLabId() != null && req.getLabMemberId() != null
                    && StringUtils.isNotBlank(req.getUsageTime()),"请求参数缺失！");
            labId=req.getLabId();
            labMemberId=req.getLabMemberId();
            usageTime=new Date(Long.valueOf(req.getUsageTime()));
        }

        //取用清单列表
        List<KitUsageGroup> result=kitUsageLogic.getUsageList(labId,labMemberId,usageTime);


        return ResponseVo.success(result);
    }

    /**
     * 移除清单中的项目
     *
     * @return
     */
    @AspectLog
    @RequestMapping(value="/take/remove", method=RequestMethod.POST)
    public ResponseVo removeInventoryFromTakeList(@RequestBody KitUsageRemoveReq req,@RequestHeader(name=StarterConstant.TOKEN) String token) {

        Assert.isTrue(!CollectionUtils.isEmpty(req.getItemIds()) && !StringUtils.isBlank(token),"请求参数缺失！");

        UserInfoVo userInfo=usersLogic.getUserByToken(token);

        kitUsageLogic.removeInventoryFromTakeList(req.getItemIds(),userInfo.getLabId(),userInfo.getLabMemberId());

        return ResponseVo.success();
    }

    /**
     * 取用删除
     *
     * @return
     */
    @AspectLog
    @RequestMapping(value="/delete", method=RequestMethod.DELETE)
    public ResponseVo deleteKitUsage(Long usageId,@RequestHeader(name=StarterConstant.TOKEN) String token) {

        Assert.isTrue(usageId!=null && !StringUtils.isBlank(token),"请求参数缺失！");

        UserInfoVo userInfo=usersLogic.getUserByToken(token);

        boolean rs = kitUsageLogic.deleteKitUsage(usageId,userInfo.getLabId(),userInfo.getLabMemberId());

        return ResponseVo.success();
    }

    /**
     * 取用历史列表
     *
     * @return
     */
    @RequestMapping(value="/usage/history", method=RequestMethod.GET)
    public ResponseVo getUsageHistoryList(@RequestParam(defaultValue="1") Integer pageNum,@RequestParam(defaultValue="10") Integer pageSize,@RequestHeader(name=StarterConstant.TOKEN) String token) {

        UserInfoVo userInfo=usersLogic.getUserByToken(token);

        //取用清单列表
        PageVo<KitUsageGroup> result=kitUsageLogic.getUsageHistoryList(userInfo.getLabId(),userInfo.getLabMemberId(),pageNum,pageSize);

        return ResponseVo.success(result);
    }

    /**
     * 未登录扫码查询（扫描试剂条形码）
     *
     * @return
     */
    @RequestMapping(value="/usage/inventroy", method=RequestMethod.GET)
    public ResponseVo getInventroy(Long inventoryId) {

        Assert.notNull(inventoryId,"请求参数缺失！");

        KitUsageWithKitInfo kitUsageWithKitInfo=kitUsageLogic.getKitUsageResp(inventoryId);

        return ResponseVo.success(kitUsageWithKitInfo);
    }

    /**
     * 添加Kit到取用清单
     *
     * @return
     */
    @AspectLog
    @RequestMapping(value="/take/kit/add", method=RequestMethod.POST)
    public ResponseVo addKitToTakeList(@RequestBody KitUsageAdd kitUsageAdd,@RequestHeader(value=StarterConstant.TOKEN) String token) {
        if(StringUtils.isBlank(token) || kitUsageAdd == null){
            throw new BrillilabException(ResultEnum.USER_NOT_LOGIN);
        }
        Long kitId=kitUsageAdd.getKitId();
        Long groupId=kitUsageAdd.getGroupId();
        BigDecimal amount=kitUsageAdd.getAmount();
        Assert.notNull(kitId,"kitId is null");
        Assert.notNull(groupId,"groupId is null ");
        Assert.notNull(amount,"amount is null");
        Assert.isTrue(amount.compareTo(BigDecimal.valueOf(0)) >= 0,"amount can not less than 0");
        UserInfoVo info=usersLogic.getUserByToken(token);

        Kit kit=kitService.selectById(kitId);
        Assert.isTrue(kit.getLabId().equals(info.getLabId()),"本实验室不存在该试剂");

        String endPoint = token.split("_")[0];

        kitUsageLogic.addKitGroupInventoryToTakeOrTaking(kitId,groupId,amount,info,KitTakeType.TAKE_TO_LIST,endPoint);

        return ResponseVo.success();
    }

    /**
     * 取用Kit
     *
     * @return
     */
    @AspectLog
    @RequestMapping(value="/usage/kit/add", method=RequestMethod.POST)
    public ResponseVo addKitToUsageList(@RequestBody KitUsageAdd kitUsageAdd,@RequestHeader(value=StarterConstant.TOKEN) String token) {
        if(StringUtils.isBlank(token) || kitUsageAdd == null){
            throw new BrillilabException(ResultEnum.USER_NOT_LOGIN);
        }
        Long kitId=kitUsageAdd.getKitId();
        Long groupId=kitUsageAdd.getGroupId();
        BigDecimal amount=kitUsageAdd.getAmount();
        Assert.notNull(kitId,"kitId is null");
        Assert.notNull(groupId,"groupId is null ");
        Assert.notNull(amount,"amount is null");
        Assert.isTrue(amount.compareTo(BigDecimal.valueOf(0)) >= 0,"amount can not less than 0");
        UserInfoVo info=usersLogic.getUserByToken(token);

        Kit kit=kitService.selectById(kitId);
        Assert.isTrue(kit.getLabId().equals(info.getLabId()),"本实验室不存在该试剂");

        String endPoint = token.split("_")[0];

        kitUsageLogic.addKitGroupInventoryToTakeOrTaking(kitId,groupId,amount,info,KitTakeType.TAKE_TO_USE,endPoint);

        return ResponseVo.success();
    }

    /**
     * 获取试剂首页历史、取用、清单统计数据
     *
     * @param token
     * @return
     */
    @RequestMapping(value="/count", method=RequestMethod.GET)
    public ResponseVo getKitUsageCountVo(@RequestHeader(value=StarterConstant.TOKEN) String token) {

        Assert.isTrue(!StringUtils.isBlank(token),"请求参数缺失！");

        UserInfoVo userInfo=usersLogic.getUserByToken(token);

        KitUsageCountVo kitUsageCountVo=kitUsageLogic.getKitUsageCountVo(userInfo.getLabId(),userInfo.getLabMemberId());

        return ResponseVo.success(kitUsageCountVo);
    }

    /**
     * 获取试剂使用状态与使用人
     *
     * @param kitId
     * @return
     */
    @RequestMapping(value="/state", method=RequestMethod.GET)
    public ResponseVo getKitUsageState(Long kitId,Long groupId,Long inventoryId) {

        Assert.isTrue(kitId != null || inventoryId != null,"请求参数缺失！");

        KitUsageState state=kitUsageLogic.getKitUsageState(kitId,groupId,inventoryId);

        return ResponseVo.success(state);
    }

    /**
     * 批量获取试剂使用状态与使用人
     *
     * @param usageIds
     * @return
     */
    @RequestMapping(value="/state/list", method=RequestMethod.POST)
    public ResponseVo getKitUsageState(@RequestBody List<Long> usageIds) {

        Assert.isTrue(!CollectionUtils.isEmpty(usageIds) ,"请求参数缺失！");

        List<KitUsageState> states=kitUsageLogic.getKitUsageStateList(usageIds);

        return ResponseVo.success(states);
    }

    /**
     * 库存余量修改
     *
     * @return
     */
    @AspectLog
    @RequestMapping(value="/inventory/amount", method=RequestMethod.GET)
    public ResponseVo modifyInventoryAmount(Long usageId,BigDecimal amount,@RequestHeader(value=StarterConstant.TOKEN) String token) {

        Assert.isTrue(usageId != null && amount != null,"请求参数缺失！");
        Assert.isTrue(amount.compareTo(BigDecimal.valueOf(0)) >= 0,"余量不能为负数！");

        UserInfoVo userInfo=usersLogic.getUserByToken(token);

        boolean b=kitUsageLogic.modifyInventoryAmount(usageId,amount,userInfo);
        Assert.isTrue(b,"业务操作失败！");

        return ResponseVo.success();
    }

    /**
     * 获取打印清单数据
     */
    @RequestMapping(value="/print/list", method=RequestMethod.GET)
    public ResponseVo printList(@RequestHeader(value=StarterConstant.TOKEN) String token) {

        Assert.isTrue(StringUtils.isNotBlank(token),"参数缺失！");

        UserInfoVo userInfo=usersLogic.getUserByToken(token);
        //取用清单列表
        PrintPreviewVo result=kitUsageLogic.getPrintList(userInfo.getLabId(),userInfo.getLabMemberId(),userInfo.getName());

//        if(result != null){
//            String qrUrl="/api/usage/list"
//                    + "?labId=" + userInfo.getLabId() + "&labMemberId=" + userInfo.getLabMemberId() + "&usageTime=" + result.getUsageTime().getTime();
//
//            result.setQrUrl(qrUrl);
//        }

        return ResponseVo.success(result);
    }

    /**
     * 取用开锁 （返回开锁列表，24小时未开门，状态为变为取用TAKE）
     */
    @RequestMapping(value="/unlock", method=RequestMethod.POST)
    public ResponseVo sendTakingUnlockInfo(@RequestBody JSONObject params,@RequestHeader(value=StarterConstant.TOKEN) String token) {

        Assert.isTrue(params != null
                && params.get("usageIds") != null
                && ((ArrayList) params.get("usageIds")).size() > 0,"请求参数缺失！");
        List<Long> kitUsageIds=(List<Long>) ((ArrayList) params.get("usageIds")).stream().map(e -> Long.valueOf((Integer) e)).collect(Collectors.toList());
        UserInfoVo userInfo=usersLogic.getUserByToken(token);
        kitUsageLogic.sendTakingUnlockInfoToAio(kitUsageIds,userInfo);
        return ResponseVo.success();
    }

    /**
     * 取用/归还开锁
     */
    @RequestMapping(value="/use/unlock",method=RequestMethod.POST)
    public ResponseVo unlock(@RequestBody List<UsageUnlockReq> params,@RequestHeader(value=StarterConstant.TOKEN) String token) {

        Assert.isTrue(params != null &&params.size() > 0,"请求参数缺失！");
        UserInfoVo userInfo=usersLogic.getUserByToken(token);

        List<Long> take=params.stream().filter(e -> UnLockOperateEnum.TAKE.getValue().equals(e.getOperate())).map(UsageUnlockReq::getUsageId).collect(Collectors.toList());
        List<Long> use=params.stream().filter(e -> UnLockOperateEnum.RETURN.getValue().equals(e.getOperate())).map(UsageUnlockReq::getUsageId).collect(Collectors.toList());

        if(take.size()>0){
            kitUsageLogic.sendTakingUnlockInfoToAio(take,userInfo);
        }
        if(use.size()>0){
            kitUsageLogic.sendReturningUnlockInfo(use,userInfo);
        }
        return ResponseVo.success();
    }


    /**
     * 取用/归还关锁（修改取用中状态为未归还NOT_RETURN，扣除使用量，做取用记录）
     */
    @RequestMapping(value="/use/lock", method=RequestMethod.GET)
    public ResponseVo changeToNotReturnAndDeduceInv(Long deviceId,Long labId,Long labMemberId) {
        Assert.isTrue(deviceId != null && labId != null,"请求参数缺失");
        kitUsageLogic.changeToNotReturnAndDeduceInv(deviceId,labId,labMemberId);
        kitUsageLogic.changeToReturnedAndReturnRemainInv(deviceId,labId,labMemberId);
        reagentInventoryLogic.deleteLock(deviceId);
        return ResponseVo.success();
    }

    /**
     * 归还开锁（返回归还列表，24小时未开门，状态为变为未归还NOT_RETURN）
     */
    @RequestMapping(value="/return/unlock", method=RequestMethod.POST)
    public ResponseVo sendReturningUnlockInfo(@RequestBody JSONObject params,@RequestHeader(value=StarterConstant.TOKEN) String token) {

        Assert.isTrue(params != null
                && params.get("usageIds") != null
                && ((ArrayList) params.get("usageIds")).size() > 0,"请求参数缺失！");

        List<Long> kitUsageIds=(List<Long>) ((ArrayList) params.get("usageIds")).stream().map(e -> Long.valueOf((Integer) e)).collect(Collectors.toList());
        UserInfoVo userInfo=usersLogic.getUserByToken(token);
        kitUsageLogic.sendReturningUnlockInfo(kitUsageIds,userInfo);
        return ResponseVo.success();
    }

    /**
     * 从未归还清单加入归还中清单
     */
    @AspectLog
    @RequestMapping(value="/usage/return", method=RequestMethod.POST)
    public ResponseVo addToReturning(@RequestBody KitUsageReturnList kitUsageReturnList,@RequestHeader(name=StarterConstant.TOKEN) String token) {

        Assert.isTrue(kitUsageReturnList != null,"请求参数缺失！");
        List<KitUsageReturn> items=kitUsageReturnList.getItems();
        Assert.isTrue(!CollectionUtils.isEmpty(items),"请求参数缺失！");

        UserInfoVo userInfo=usersLogic.getUserByToken(token);

        String endPoint = token.split("_")[0];

        doReturn(items,userInfo,endPoint);

        return ResponseVo.success();
    }

    private void doReturn(List<KitUsageReturn> items,UserInfoVo userInfo,String endPoint) {
        List<KitUsageReturn> hasLocks=new ArrayList<>();
        List<KitUsageReturn> noLocks=new ArrayList<>();
        List<Long> invIds=items.stream().map(KitUsageReturn::getUsageId).collect(Collectors.toList());
        List<ItemLock> itemLocks=deviceService.selectDeviceLockMapByUsageId(invIds);
        items.forEach(kitUsageReturn -> {
            Assert.isTrue(kitUsageReturn.getUsageId() != null,"请求参数缺失！");
            ItemLock itemLock=itemLocks.stream().filter(e -> e.getId().equals(kitUsageReturn.getUsageId())).findFirst().orElse(null);
            if(itemLock != null && itemLock.getHasLock().equals(1)){
                hasLocks.add(kitUsageReturn);
            } else {
                noLocks.add(kitUsageReturn);
            }
        });

        //添加到归还中清单
        if(noLocks.size() > 0){
            kitUsageLogic.returnInventory(userInfo,noLocks,endPoint);
        }

        if(hasLocks.size() > 0){
            kitUsageLogic.addToReturning(userInfo,hasLocks);
        }
    }

    /**
     * 归还中清单
     */
    @RequestMapping(value="/returning/list", method=RequestMethod.GET)
    public ResponseVo getReturningList(@RequestHeader(name=StarterConstant.TOKEN) String token) {

        Assert.isTrue(!StringUtils.isBlank(token),"请求参数缺失！");

        UserInfoVo userInfo=usersLogic.getUserByToken(token);

        //取用清单列表
        List<KitTakeDeviceList> result=kitUsageLogic.getReturningList(userInfo.getLabId(),userInfo.getLabMemberId());

        return ResponseVo.success(result);
    }


    /**
     * 实验步骤中取用
     * @param params
     * @param token
     * @return
     */
    @AspectLog
    @RequestMapping(value="/experiment/step/take", method=RequestMethod.POST)
    public ResponseVo experimentStepTake(@RequestBody JSONObject params,@RequestHeader(name=StarterConstant.TOKEN) String token) {

        Long experimentId = params.getLong("experimentId");
        Long phaseId = params.getLong("phaseId");
        Long stepId = params.getLong("stepId");
        Assert.isTrue(experimentId != null && phaseId != null && stepId != null && StringUtils.isNotBlank(token),"请求参数缺失！");

        UserInfoVo userInfo=usersLogic.getUserByToken(token);

        //实验步骤中试剂取用逻辑
        List<ExperimentStepReagent> noGroup=kitUsageLogic.executeExperimentStepReagentTake(experimentId,phaseId,stepId,userInfo.getLabId(),userInfo.getLabMemberId(),userInfo.getName());

        return ResponseVo.success();
    }

    /**
     * 实验中取用列表
     *
     * @param experimentId
     * @param token
     * @return
     */
    @RequestMapping(value="/experiment/take/list", method=RequestMethod.GET)
    public ResponseVo experimentTakeList(Long experimentId,@RequestHeader(name=StarterConstant.TOKEN) String token) {

        Assert.isTrue(experimentId != null && StringUtils.isNotBlank(token),"请求参数缺失！");

        UserInfoVo userInfo=usersLogic.getUserByToken(token);

        //实验中取用列表逻辑
        ExperimentKitUsageListVo usageListVo=kitUsageLogic.getExperimentKitUsageListVo(experimentId,userInfo.getLabId(),userInfo.getLabMemberId());

        return ResponseVo.success(usageListVo);
    }

    /**
     * 打印预览
     *
     * @param usages
     * @param token
     * @return
     */
    @RequestMapping(value="/print/preview", method=RequestMethod.POST)
    public ResponseVo printPreview(@RequestBody List<PrintPreviewGet> usages,@RequestHeader(name=StarterConstant.TOKEN) String token) {

        Assert.isTrue(usages != null && usages.size() > 0 && StringUtils.isNotBlank(token),"请求参数缺失！");

        UserInfoVo userInfo=usersLogic.getUserByToken(token);

        PrintPreviewVo printPreviewVo=kitUsageLogic.getPrintPreviewList(usages,userInfo);

        return ResponseVo.success(printPreviewVo);
    }

    /**
     * 删除试剂打印预览
     *
     * @param kitId
     * @param token
     * @return
     */
    @RequestMapping(value="/kitDelete/print/preview", method=RequestMethod.GET)
    public ResponseVo printInventoryPreview(Long kitId,@RequestHeader(name=StarterConstant.TOKEN) String token) {

        Assert.isTrue(kitId != null && StringUtils.isNotBlank(token),"请求参数缺失！");

        UserInfoVo userInfo=usersLogic.getUserByToken(token);

        PrintPreviewVo printPreviewVo=kitUsageLogic.getInventoryPrintPreviewList(kitId,userInfo);

        return ResponseVo.success(printPreviewVo);
    }


    /**
     * 试剂可选位置清单
     *
     * @param inventoryId
     * @param token
     * @return
     */
    @RequestMapping(value="/inventory/choose/list", method=RequestMethod.GET)
    public ResponseVo inventoryChooseList(Long inventoryId,@RequestHeader(name=StarterConstant.TOKEN) String token) {

        Assert.isTrue(inventoryId != null && StringUtils.isNotBlank(token),"请求参数缺失！");

        UserInfoVo userInfo=usersLogic.getUserByToken(token);

        List<InventoryChooseVo> chooseVoList=kitUsageLogic.getInventoryChooseList(inventoryId,userInfo.getLabId(),userInfo.getLabMemberId());

        return ResponseVo.success(chooseVoList);
    }

    /**
     * 修改取用清单中位置信息
     *
     * @param params
     * @param token
     * @return
     */
    @AspectLog
    @RequestMapping(value="/inventory/change", method=RequestMethod.PUT)
    public ResponseVo inventoryChange(@RequestBody JSONObject params,@RequestHeader(name=StarterConstant.TOKEN) String token) {

        Long usageId ,inventoryId;
        usageId = params.getLong("usageId");
        inventoryId = params.getLong("inventoryId");

        Assert.isTrue(usageId != null && inventoryId != null && StringUtils.isNotBlank(token),"请求参数缺失！");

        UserInfoVo userInfo=usersLogic.getUserByToken(token);

        KitUsageItemPrintVo printVo=kitUsageLogic.changeUsageInventory(usageId,inventoryId,userInfo.getLabId(),userInfo.getLabMemberId());

        return ResponseVo.success();
    }

    /**
     * 清单数量
     * @param token
     * @return
     */
    @RequestMapping(value="/num", method=RequestMethod.GET)
    public ResponseVo kitUsageCount(@RequestHeader(name=StarterConstant.TOKEN) String token){

        UserInfoVo userInfo=usersLogic.getUserByToken(token);

        int count = kitUsageLogic.getTakingListCount(userInfo.getLabId(),userInfo.getLabMemberId());

        HashMap<String, Integer> rsMap=new HashMap<>();
        rsMap.put("num",count);

        return ResponseVo.success(rsMap);
    }

    /**
     * 实验清单数量
     * @param experimentId
     * @param token
     * @return
     */
    @RequestMapping(value="/experiment/num" , method=RequestMethod.GET)
    public ResponseVo experimentKitUsageCount(Long experimentId,@RequestHeader(StarterConstant.TOKEN) String token){

        Assert.isTrue(experimentId!=null && StringUtils.isNotBlank(token),"请求参数缺失！");

        UserInfoVo userInfo=usersLogic.getUserByToken(token);

        int count=kitUsageLogic.getExperimentListCount(userInfo.getLabId(),userInfo.getLabMemberId(),experimentId);

        HashMap<String, Integer> rsMap=new HashMap<>();
        rsMap.put("num",count);

        return ResponseVo.success(rsMap);
    }

    /**
     * 取用归还中列表
     * @param token
     * @return
     */
    @RequestMapping(value="/takingAndReturning/list",method=RequestMethod.GET)
    public ResponseVo takingAndReturningList(@RequestHeader(name=StarterConstant.TOKEN) String token){

        Assert.isTrue(StringUtils.isNotBlank(token),"请求参数缺失！");

        UserInfoVo userInfo=usersLogic.getUserByToken(token);

        List<KitTakeDeviceList> result=kitUsageLogic.getTakingAndReturningList(userInfo.getLabId(),userInfo.getLabMemberId());

        return ResponseVo.success(result);
    }

    /**
     * 使用历史
     * @param pageNum
     * @param pageSize
     * @param token
     * @return
     */
    @RequestMapping(value="/history",method=RequestMethod.GET)
    public ResponseVo history(Integer pageNum, Integer pageSize, @RequestHeader(name=StarterConstant.TOKEN) String token){

        Assert.isTrue(pageNum!=null && pageSize!=null && StringUtils.isNotBlank(token),"请求参数缺失！");

        UserInfoVo userInfo=usersLogic.getUserByToken(token);

        PageVo<KitUsageVo> result=kitUsageLogic.getUsageHistoryPage(userInfo.getLabId(),userInfo.getLabMemberId(),pageNum,pageSize);

        return ResponseVo.success(result);
    }

    /**
     * 漏取/漏还
     * @param operates
     * @param token
     * @return
     */
    @RequestMapping(value="/forget/takeOrReturn",method=RequestMethod.POST)
    public ResponseVo forgetTakeOrReturn(@RequestBody List<KitUsageOperateVo> operates,@RequestHeader(name=StarterConstant.TOKEN) String token){

        Assert.isTrue(operates != null && operates.size() > 0 && StringUtils.isNotBlank(token),"请求参数缺失！");

        UserInfoVo userInfo=usersLogic.getUserByToken(token);

        operates.forEach(operate -> {
            Assert.isTrue(operate.getUsageId() != null && operate.getOperation() != null,"请求参数缺失！");
        });

        kitUsageLogic.doForgetTakeOrReturn(operates,userInfo.getLabId(),userInfo.getLabMemberId());

        return ResponseVo.success();
    }

    /**
     * 打印预览取用Kit
     * @param kitId
     * @param groupId
     * @param amount
     * @param token
     * @return
     */
    @RequestMapping(value="/kitUse/print/preview",method=RequestMethod.GET)
    public ResponseVo kitUsePrintPreview(Long kitId,Long groupId,BigDecimal amount,@RequestHeader(name=StarterConstant.TOKEN) String token){

        Assert.isTrue(kitId!=null && groupId!=null && amount!=null && StringUtils.isNotBlank(token),"请求参数缺失！");

        UserInfoVo userInfo=usersLogic.getUserByToken(token);

        PrintPreviewVo printPreviewVo=kitUsageLogic.getKitUsePrintPreviewList(kitId,groupId,amount,userInfo);

        return ResponseVo.success(printPreviewVo);
    }

    /**
     * 取用归还中确认
     * @param usageIds
     * @param token
     * @return
     */
    @RequestMapping(value="/operate/confirm",method=RequestMethod.POST)
    public ResponseVo operateConfirm(@RequestBody List<Long> usageIds,@RequestHeader(name=StarterConstant.TOKEN) String token){

        Assert.isTrue(!CollectionUtils.isEmpty(usageIds) && StringUtils.isNotBlank(token),"请求参数缺失！");

        UserInfoVo userInfo=usersLogic.getUserByToken(token);

        kitUsageLogic.operateConfirm(usageIds,userInfo.getLabId(),userInfo.getLabMemberId());

        return ResponseVo.success();

    }
}
